var AV = require('leanengine');

const sensitive = {"status":0,sensitive:""};
const rp = require('request-promise')
const SensitiveWords = require('./lib/sensitive-words');
const sensitiveBase = new SensitiveWords();
const baseWords = require('./lib/words');
 
sensitiveBase.addWords(baseWords.baseWords);



postJson = (body,url) =>{
    let uri = process.env.API_BASE_DOMAIN + '/leancloud/hook/'+url;
    let options = {
        method: 'POST',
        json: true,
        uri: uri,
        body: body
    }
    console.log(uri);
    return rp(options)
        .then(data => {
            console.log(data);
            return {};
        })
        .catch(err => {
            return {};
        });
};

//处理消息结构体，是否是弹幕
isScreen = (content) => {
  return true;
}

//处理消息结构体，是否是弹幕
isScreen = (content) => {
      return false;
   }

//加入高级用户是否弹幕，是否是弹幕
isJoinRoom = (json) => {
    return true;
}
filterSensitive = (content) =>{
  if(sensitive.sensitive === ""){
    return false;
  }
  let sensitiveContent =new RegExp(sensitive.sensitive,'g');
    return sensitiveContent === null?[]:sensitiveContent;
}
// 用户进入直播间
AV.Cloud.onIMConversationAdd((request) => {
  let params = request.params;
    console.log('用户进入直播间',  request.params);
    postJson(params,'conversationAdd');
});

// 离开直播间被踢出
AV.Cloud.onIMConversationRemove((request) => {
  let params = request.params;
  console.log('用户进入直播间',  request.params);
  postJson(params,'conversationRemove');
});

//聊天室发送消息
AV.Cloud.onIMMessageReceived((request) => {
  let content = request.params.content;
  console.log('params',  request.params);
  let sensitiveContent = sensitiveBase.wordsDfa(content);
  if(sensitiveContent.length>0){  //包含基础敏感词
    request.params.sensitiveContent = sensitiveContent;
    request.params.sensitiveSource = 1;  //敏感词源
    postJson(content,'messageReceived');
    console.log('params-send',  request.params);
    return { "drop": true, code: -1, detail:'包含敏感词' };
  }else{
    if(sensitive.status === 0){
      // 没有从本地服务器获取过敏感词 去服务器获取
      postJson(content,'getSensitiveWords');
      return { content: content }
    }else{
      if(filterSensitive(content).length>0){  //包含自定义敏感词
        request.params.sensitiveContent = sensitiveContent;
        request.params.sensitiveSource = 2;  //敏感词源
        postJson(request.params,'messageReceived');
        return { "drop": true, code: -1, detail:'包含敏感词' };
      }else{
        return  { content: content }
      }
    }
  }
   
});

//自定义函数，设置自定义敏感词 需要全量
AV.Cloud.define('putSensitive', { fetchUser: false, internal: false }, function (request) {
  sensitive.sensitive = request.params.content;
  sensitive.status = 1;
  return sensitive;
});

//自定义函数，获取自定义敏感词
AV.Cloud.define('getSensitive', { fetchUser: false, internal: false }, function (request) {
  return sensitive;
});

AV.Cloud.define('_messageSent', function(request) {
  console.log('_messageSent',  request.params);
 postJson(request.params,'messageSent');
});


 